const fs = require("fs");
const uuid = require('short-uuid');
const gcoord = require('gcoord')

const json = JSON.parse(fs.readFileSync("./file.geojson").toString("utf-8"));

const getID = () => uuid.generate()

const result = {
  pipeNodeList: [],
  pipeLineGwList: [],
}

for(const feature of json.features) {
  let drainageType = ""
  if(feature.properties.layer === "WS-LINE") {
    drainageType = 1
  }
  if (feature.properties.layer === "YS-LINE") {
    drainageType = 2
  }
  if (!drainageType || feature.geometry.type !== 'LineString') continue

  const [startPoint, endPoint] = feature.geometry.coordinates
  const startPointObj  = {
    lng: startPoint[0],
    lat: startPoint[1],
    alt: startPoint[2],
    drainageType,
  }
  const endPointObj = {
    lng: endPoint[0],
    lat: endPoint[1],
    alt: startPoint[2],
    drainageType,
  }
  if (startPointObj.alt < endPointObj.alt) {
    const { lng, lat } = startPointObj
    startPointObj.lng = endPointObj.lng
    startPointObj.lat = endPointObj.lat
    endPointObj.lng = lng
    endPointObj.lat = lat
  }

  const startCheck = result.pipeNodeList.find(i => i.lng === startPoint[0] && i.lat === startPoint[1] && i.drainageType === drainageType)
  const endCheck = result.pipeNodeList.find(i => i.lng === endPoint[0] && i.lat === endPoint[1] && i.drainageType === drainageType)
  if (!startCheck) {
    startPointObj.id = getID()
    result.pipeNodeList.push(startPointObj)
  } else {
    startPointObj.id = startCheck.id
  }
  if (!endCheck) {
    endPointObj.id = getID()
    result.pipeNodeList.push(endPointObj)
  } else {
    endPointObj.id = endCheck.id
  }

  result.pipeLineGwList.push({
    id: getID(),
    startNodeId: startPointObj.id,
    endNodeId: endPointObj.id,
  });
}

fs.writeFileSync('result-wgs84.json', JSON.stringify(result))

result.pipeNodeList.forEach(i => {
  const [lng, lat] = gcoord.transform([i.lng, i.lat], gcoord.WGS84, gcoord.GCJ02)
  i.lng = lng
  i.lat = lat
})
fs.writeFileSync('result-gcj02.json', JSON.stringify(result))